using MediatR;
using TerritoryGame.Application.Commands;
using TerritoryGame.Domain.Repositories;

namespace TerritoryGame.Application.Handlers.CommandHandlers;

public class DeleteRoomCommandHandler : IRequestHandler<DeleteRoomCommand, DeleteRoomResult>
{
    private readonly IGameRoomRepository _gameRoomRepository;

    public DeleteRoomCommandHandler(IGameRoomRepository gameRoomRepository)
    {
        _gameRoomRepository = gameRoomRepository;
    }

    public async Task<DeleteRoomResult> Handle(DeleteRoomCommand request, CancellationToken cancellationToken)
    {
        try
        {
            // 用 RoomCode 删除房间
            var success = await _gameRoomRepository.DeleteRoomByCodeAsync(request.RoomCode);

            return new DeleteRoomResult
            {
                Success = success,
                ErrorMessage = success ? null : "Failed to delete room"
            };
        }
        catch (Exception ex)
        {
            return new DeleteRoomResult
            {
                Success = false,
                ErrorMessage = ex.Message
            };
        }
    }
}
